package edu.spec.yjx.service.impl;

import edu.spec.yjx.dao.iface.INewsDao;
import edu.spec.yjx.model.News;
import edu.spec.yjx.service.iface.INewsService;
import org.madgecko.basic.model.Pager;
import org.madgecko.basic.model.SystemContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;


/**
 * Author       : MadFrog
 * Date         : 2018/11/10 18:01
 * Description  : 消息类的服务接口的实现
 */
@Service
public class NewsService implements INewsService {

    @Autowired
    private INewsDao newsDao;

    @Override
    public News add(News news) {
        return newsDao.add(news);
    }

    @Override
    public void delete(Integer id) {
        News news = newsDao.load(id);
        newsDao.delete(id);
        // 删除文章包含的图片、文件
        String content = news.getContent();
        int i=0;
        while (i>=0){
            i = content.indexOf("resources/upload/images", i+1);
            // 图片的扩展名可能是3个字符，也可能是4个字符
            if(i>0){
                String imagePath3 = content.substring(i, i+65);
                String imagePath4 = content.substring(i, i+66);
                tryToDeleteFile(imagePath3);
                tryToDeleteFile(imagePath4);
            }
        }

        int j=0;
        while (j>=0){
            j = content.indexOf("resources/upload/files", j+1);
            // 文件的扩展名可能是2个字符，也可能是3个字符，也可能是4个字符
            if(j>0){
                String imagePath2 = content.substring(j, j+54);
                String imagePath3 = content.substring(j, j+55);
                String imagePath4 = content.substring(j, j+56);
                tryToDeleteFile(imagePath2);
                tryToDeleteFile(imagePath3);
                tryToDeleteFile(imagePath4);
            }
        }
    }

    @Override
    public News update(News news) {
        return newsDao.update(news);
    }

    @Override
    public News load(Integer id) {
        return newsDao.load(id);
    }

    @Override
    public Pager<News> findByCon(String keyword) {
        return newsDao.findByCon(keyword);
    }

    private void tryToDeleteFile(String reltivePath){
        String absolutePath = SystemContext.getSystemPath() + "/" + reltivePath;
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + absolutePath + "成功！");
            } else {
                System.out.println("删除单个文件" + absolutePath + "失败！");
            }
        } else {
            System.out.println("删除单个文件失败：" + absolutePath + "不存在！");
        }
    }

}
